package com.alipay.sdk.abcphaima;

import android.app.Application;
import android.content.Context;
import android.os.Bundle;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.iot.bpaas.api.BPaaSApi;
import com.alipay.iot.bpaas.api.BPaaSInitCallback;
import com.alipay.iot.bpaas.api.InnerApi;
import com.alipay.iot.bpaas.api.ipc.IpcChannel;
import com.alipay.iot.bpaas.api.ipc.IpcListener;
import com.alipay.iot.bpaas.api.service.BPaaSCallback;
import com.alipay.iot.bpaas.api.service.BPaaSResponse;
import com.alipay.iot.sdk.APIManager;
import com.alipay.iot.sdk.utils.DetectionIotSystem;
import com.alipay.iot.sdk.utils.ErrorCode;
import com.alipay.sdk.abcphaima.bean.ConfigData;
import com.alipay.sdk.util.DeviceUtil;
import com.alipay.sdk.util.LogUtil;
import com.alipay.sdk.util.TextUtil;

/**
 * @ProjectName: 团餐
 * @ClassName: AbcpHaima
 * @Description: java类作用描述
 * @Author: bd-001935
 * @CreateDate: 2022/8/15 4:06 下午
 */
public class AbcpHM {

    private ConfigData mConfigData;
    public static String abcpAppId = "";
    public static String abcpAppVersion = "";

    private static AbcpHM Instance;

    private AbcpInitCallback mAbcpInitCallback;

    /**
     * 标记abcp是否初始化成功
     */
    private boolean abcpInitSuccess = false;
    private Context context;

    public static synchronized AbcpHM getInstance() {
        if (Instance == null) {
            Instance = new AbcpHM();
        }
        return Instance;
    }

    public boolean isAbcpInitSuccess() {
        return abcpInitSuccess;
    }

    public void init(Application context, ConfigData configData, AbcpInitCallback callback) {
        init(context, configData, true, callback);
    }

    public void init(Application context, ConfigData configData, boolean isAbcp, AbcpInitCallback callback) {
        mAbcpInitCallback = callback;
        mConfigData = configData;
        this.context = context;

        if (mConfigData == null) {
            LogUtil.d("ABCP HAIMA init ConfigData is null");
            return;
        }

        abcpAppId = mConfigData.abcpAppId;
        abcpAppVersion = mConfigData.abcpAppVersion;

        LogUtil.d("Smile version is " + DeviceUtil.getSmileAPPVersion(context));
        LogUtil.d("isAbcp " + isAbcp);

        //初始化IoT SDK
        if (DetectionIotSystem.getInstance().ifInstallIotService(context)
                == ErrorCode.LOCAL_NO_ERROR &&
                DetectionIotSystem.getInstance().ifInstallIotMaster(context)
                        == ErrorCode.LOCAL_NO_ERROR) {
            String appId;
            if (isAbcp) appId = configData.abcpAppId;
            else appId = configData.partnerId;
            try {
                APIManager.getInstance().initialize(context, appId, b -> {
                    if (b) {
                        LogUtil.d("IoT SDK初始化成功 appid " + appId);
                        if (isAbcp)
                            initABCP();
                        else {
                            if (mAbcpInitCallback != null)
                                mAbcpInitCallback.onInitResult(true);
                        }
                    } else {
                        initFail();
                    }
                });
            } catch (APIManager.APIInitException e) {
                LogUtil.printStackTrace(e);
                initFail();
            }
        } else {
            initFail();
        }
    }

    private void initFail() {
        LogUtil.d("初始化失败 appid " + mConfigData.abcpAppId);
        abcpInitSuccess = false;
        if (mAbcpInitCallback != null)
            mAbcpInitCallback.onInitResult(false);
    }

    private void initABCP() {
        LogUtil.d("ABCP相关配置信息 APPID = " + abcpAppId
                + " APP_VERSION = " + abcpAppVersion);
        //ABCP SDK初始化  传入在IoT开放平台上申请到的Appid、应用版本号信息
        BPaaSApi.getInstance().init(context,
                abcpAppId,
                abcpAppVersion,
                null,
                new BPaaSInitCallback() {
                    @Override
                    public void onSuccess() {
                        LogUtil.d("初始化ABCP SDK 成功");
                        // 初始化C屏服务
                        initSmileC();
                        // 添加IpcListener，用于监听与C屏app的连接，便于做业务恢复，比如重新初始化C屏app
                        InnerApi.addIpcListener(mIpcListener);
                    }

                    @Override
                    public void onFail(String subCode) {
                        LogUtil.d("初始化ABCP  SDK 失败 subCode = " + subCode);
                        initFail();
                    }
                });
    }

    /**
     * 初始化C屏服务
     */
    private void initSmileC() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("logicGroupID", mConfigData.logicGroupID);           // 人脸库ID，需替换成ISV自身的logicGroupID
        jsonObject.put("industryBizType", mConfigData.industryBizType);     // 团餐场景标识：college=高校；business=企业
        jsonObject.put("partnerId", mConfigData.partnerId);                 // 服务商Pid,开放平台的账户中心可查看获取 （不清楚可钉钉群内询问技术支持）
        jsonObject.put("merchantId", mConfigData.merchantId);               // 商户id（不清楚可钉钉群内询问技术支持）
        jsonObject.put("merchantName", mConfigData.merchantName);           // 商户名（不清楚可钉钉群内询问技术支持）
        jsonObject.put("isvName", mConfigData.isvName);                     // 服务商名称（不清楚可钉钉群内询问技术支持）
        jsonObject.put("useOfflinePay", true);                              // 是否采用异步方案 （离线结果页）
        jsonObject.put("uploadTimeOutSecs", mConfigData.uploadTimeOutSecs); // 等待结果页支付查询超时时间，默认20s
        jsonObject.put("enableScanCode", true);                             // 是否开启扫码功能
        if (mConfigData.enableOfflineFace)
            jsonObject.put("enableOffFtoken", mConfigData.enableOfflineFace);// 是否开启离线刷脸

        startCanteenBPaaSService("canteen", "init",
                jsonObject, new BPaaSCallback() {
                    @Override
                    public void onResponse(BPaaSResponse response) {
                        LogUtil.d("初始化C屏服务 出参" + response);
                        if (response.getCode() == BPaaSResponse.RESULT_CODE_SUCCESS) {
                            Bundle result = response.getResult();
                            boolean success = result.getBoolean("success");
                            LogUtil.d("初始化C屏服务 出参" + result.toString());
                            if (success) {
                                //C屏服务初始化成功
                                abcpInitSuccess = true;
                                if (mAbcpInitCallback != null)
                                    mAbcpInitCallback.onInitResult(true);
                            } else {
                                String subCode = result.getString("subCode");
                                String subMessage = result.getString("subMessage");
                                LogUtil.d("初始化C屏服务 出参"
                                        + "\nsubCode = " + subCode
                                        + "\nsubMessage = " + subMessage);
                                //C屏服务初始化失败，原因：subMessage
                                initFail();
                            }
                        } else {
                            initFail();
                        }
                    }

                    @Override
                    public void onEvent(String s, String s1, Bundle bundle) {

                    }
                });
    }

    public void removeIpcListener() {
        InnerApi.removeIpcListener(mIpcListener);
    }

    private final IpcListener mIpcListener = new IpcListener() {
        @Override
        public void onConnected(IpcChannel ipcChannel) {
            LogUtil.d("IpcListener onConnected");
            // 监听到重新连接，需要重新初始化ABCP和C屏服务
            initABCP();
        }

        @Override
        public void onDisconnected(IpcChannel ipcChannel) {
            LogUtil.d("IpcListener onDisconnected");
        }

        @Override
        public void onConnectionFailed(IpcChannel ipcChannel) {
            LogUtil.d("IpcListener onConnectionFailed");
        }
    };

    public interface AbcpInitCallback {
        void onInitResult(boolean isSuccess);
    }

    public interface AbcpScanFaceCallback {
        void onSuccess(boolean isFace, String authCode, String barCode, String tradeNo, String sessionId, String alipayUid);

        void onFail(String code, String msg);

        void onEvent(String sessionId);
    }


    public interface AbcpLoadingCallback {
        void onSuccess(String tradeNo, String sessionId, String alipayUid);

        void onFail(String code, String msg);

        void onEvent(String sessionId);
    }


    public interface AbcpHMRequestSessionCallback {
        void onSuccess(String tradeNo, String sessionId);
    }

    public static void startCanteenBPaaSService(
            String page,
            String operateType,
            JSONObject params,
            BPaaSCallback callback) {
        Bundle bundle = new Bundle();
        bundle.putString("page", page);
        bundle.putString("operateType", operateType);
        bundle.putString("extInfo", "");
        bundle.putString("params", params.toJSONString());
        bundle.putLong(BPaaSApi.KEY_BPAAS_IPC_TIME_OUT, -1);

        LogUtil.d("startCanteenBPaaSService 入参" + bundle);

        BPaaSApi.getInstance().startBPaaSService(
                abcpAppId,
                "BPaaSCanteenTemplate",
                bundle,
                callback);
    }
}
